<template>
  <div class="search-history">
    <form action="/" class="formBar">
      <van-search
        v-model="searchValue"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @input="changeInp"
        @focus="showCom=false"
      />
    </form>
    <!-- ------------插入子组件 ---------------->
    <search-result :searchValue="searchValue" v-if="showCom"></search-result>
    <search-suggestion  @search="onSearch" :searchValue="searchValue" v-else-if="searchValue"></search-suggestion>
    <search-history
      @search="onSearch"
      :historyList="historyList"
      @delAllList="historyList=[]"
      v-else
    ></search-history>
  </div>
</template>

<script>
import searchHistory from "@/components/search/search-history";
import searchSuggestion from "@/components/search/search-suggestion";
import searchResult from "@/components/search/search-result";
import { SET_TOKEN, GET_TOKEN } from "@/utils/storage";
export default {
  //挂载子组件---------------------------------
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  data() {
    return {
      showCom: false,
      searchValue: "",
      historyList: GET_TOKEN("historyList") || []
    };
  },
  methods: {
    onSearch(val) {  //这是用户在input输入的值
      //点击历史记录的其中一项，可以跳转到搜索结果页面
    //就是吧关键词填充到input框，然后触发onsearch事件
    this.searchValue=val
      /* 
      回车：将值存入到本地缓存中，并且可以显示在history组件中
      如果数组里有重复的就删除
      */
      var index = this.historyList.findIndex(item => item == val);
      if (index != -1) {
        this.historyList.splice(index, 1);
      }
      //把输入框的值，和原数组拼接
      this.historyList = [val, ...this.historyList];
      //存储本地
      SET_TOKEN("historyList", this.historyList);
      this.$toast(val);
      this.showCom = true; //关闭result组件
    },
    onCancel() {
      // Toast("取消");
      this.$router.go(-1);
    },
    //输入框内容变化时触发
    changeInp(val) {
      // console.log(val,'aaaaaa');
      this.showCom = false;
    }
  }
};
</script>
<style scoped lang="less">
.search-history {
  /deep/.van-search__action {
    color: #fff;
  }
  .formBar {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
  }
  
}
</style>